//
//  InitLockView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/16.
//

import SwiftUI
import TLCLock

struct InitLockView: View {


    @State var serverDate: Date = Server.now()

    let device: LockDevice

    var body: some View {
        VStack {
            YxrDatePicker(title: "服务器时间", date: $serverDate)
            Spacer().frame(height: 20)
            
            YxrConfirmView {
                onTapConfirm()
            }
            
            LogView()
        }.onAppear {
            serverDate = Server.now()
        }
        .yxrNavigationTitle("添加蓝牙管理员")
    }

    func onTapConfirm() {
        let date = serverDate
        lockTask(desc: "添加蓝牙管理员") {
            let result = await device.initLock(serverDate: date, trackId: Server.testTrackId)
            if result.isSuccess {
                let value = result.value!

                let admin = value.adminPwd
                Log.info("lockKey: \(value.lockKey)")
                Log.info("adminKey: \(admin)  pwdId: \(value.adminId)")
                Log.info("romVersion: \(value.romVersion)")

                // Server.saveSecret(value.lockKey, for: model.device.macAddress)
                Server.testMac = device.macAddress
                Server.testLockkey = value.lockKey
                
                Log.warning("已自动更新设置中的Mac和密码")
            }
            return result
        }
    }
}
